-- filter-picture.lua ?????
local function convertImageToBase64(imagePath)
    print("convertImageToBase64 =>: " .. imagePath)
    local handle = io.popen('base64 -w 0 ' .. imagePath)  -- ????????? base64 ???????? base64
    local base64Image = handle:read('*a')
    handle:close()
    return base64Image
end

local function getFileExtension(filename)
  return string.match(filename, "%.([^%.]+)$")
end

local function urlDecode(s)
    s = string.gsub(s, '%%(%x%x)', function(h)
        return string.char(tonumber(h, 16))
    end)
    return s
end
 -- ???????????????????????base64
function Image(elem)
    print("----")
    print(elem.src)
    local alt_text = elem.caption
    local base_path = string.match(elem.src, "^(.-)%.md$")

    local imagePath = elem.src:gsub('^../..', '')
    if base_path then
        print("base_path:".. base_path)
        local new_src = base_path .. ".svg"
        print("new_src:".. new_src)
        imagePath = new_src:gsub('^../..', '')
        print("imagePath:".. imagePath)
     end

    print(imagePath)
    print("D:/document/hong" .. imagePath)
    local path = "D:/document/hong" .. imagePath
    print("add longpath: == " .. urlDecode(path))
    local base64Image = convertImageToBase64(urlDecode(path))
    -- print("transfer image: == " .. base64Image)
    -- ???????????
    -- local extension = urlDecode(path):match('%.([^%.]+)$')
    local extension = getFileExtension(path)
    print(extension)
    print("transfer image: == " .. extension)
    if extension == "svg" then
        elem.src = 'data:image/svg+xml;base64,' .. base64Image  -- ??????????? base64 ????
    else
        elem.src = 'data:image/png;base64,' .. base64Image  -- ??????????? base64 ????
    end
    return elem
end

return {
    { Image = Image }
}

